import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  InputAdornment,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Chip,
  IconButton,
  Menu,
  MenuList,
  MenuItem as MenuOption,
  ListItemIcon,
  ListItemText,
  Tooltip,
  Alert,
} from '@mui/material';
import {
  DataGrid,
  GridColDef,
  GridRenderCellParams,
  GridToolbar,
  GridActionsCellItem,
} from '@mui/x-data-grid';
import {
  Search as SearchIcon,
  Add as AddIcon,
  FilterList as FilterIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon,
  Visibility as ViewIcon,
  Business as BusinessIcon,
  Warning as WarningIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

import { 
  Tenant, 
  TenantFilter, 
  Status,
  PaginatedResponse,
  ApiResponse 
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { tenantService } from '@/services/tenantService';
import { PageHeader } from '@/components/common/PageHeader';
import { commonStyles } from '@/styles/utils';

const TenantListPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission } = useAuth();
  const { showToast } = useAppNotifications();

  // 状态管理
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<Status | ''>('');
  const [subscriptionFilter, setSubscriptionFilter] = useState('');
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(25);
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [actionMenuAnchor, setActionMenuAnchor] = useState<null | HTMLElement>(null);
  const [selectedTenant, setSelectedTenant] = useState<Tenant | null>(null);

  // 构建查询参数
  const queryParams = useMemo(() => {
    const params: TenantFilter & { page: number; pageSize: number } = {
      page: page + 1,
      pageSize,
    };

    if (searchQuery.trim()) {
      params.search = searchQuery.trim();
    }
    if (statusFilter) {
      params.status = statusFilter;
    }
    if (subscriptionFilter) {
      params.subscriptionPlan = subscriptionFilter;
    }

    return params;
  }, [searchQuery, statusFilter, subscriptionFilter, page, pageSize]);

  // 获取租户列表
  const {
    data: tenantData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['tenants', queryParams],
    queryFn: () => tenantService.getTenants(queryParams),
    keepPreviousData: true,
  });

  // 获取订阅套餐列表（用于筛选）
  const { data: subscriptionPlans } = useQuery({
    queryKey: ['subscription-plans'],
    queryFn: () => tenantService.getSubscriptionPlans(),
  });

  // 删除租户
  const deleteMutation = useMutation({
    mutationFn: tenantService.deleteTenant,
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '删除成功',
        message: '租户已成功删除',
      });
      queryClient.invalidateQueries(['tenants']);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '删除失败',
        message: error.message || '删除租户时发生错误',
      });
    },
  });

  // 批量删除租户
  const batchDeleteMutation = useMutation({
    mutationFn: (ids: string[]) => tenantService.batchDeleteTenants(ids),
    onSuccess: () => {
      showToast({
        type: 'success',
        title: '批量删除成功',
        message: `成功删除 ${selectedRows.length} 个租户`,
      });
      setSelectedRows([]);
      queryClient.invalidateQueries(['tenants']);
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '批量删除失败',
        message: error.message || '批量删除租户时发生错误',
      });
    },
  });

  // 状态渲染函数
  const renderStatus = (status: Status) => {
    const statusConfig = {
      active: { label: '启用', color: 'success' as const },
      inactive: { label: '禁用', color: 'error' as const },
      pending: { label: '待审核', color: 'warning' as const },
      suspended: { label: '暂停', color: 'error' as const },
    };

    const config = statusConfig[status] || statusConfig.inactive;
    return <Chip label={config.label} color={config.color} size="small" />;
  };

  // 到期状态渲染
  const renderExpiryStatus = (expiresAt?: string) => {
    if (!expiresAt) return null;

    const expiryDate = new Date(expiresAt);
    const now = new Date();
    const daysToExpiry = Math.ceil((expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

    if (daysToExpiry <= 0) {
      return (
        <Chip
          label="已到期"
          color="error"
          size="small"
          icon={<WarningIcon />}
        />
      );
    } else if (daysToExpiry <= 7) {
      return (
        <Chip
          label={`${daysToExpiry}天后到期`}
          color="warning"
          size="small"
          icon={<WarningIcon />}
        />
      );
    }

    return (
      <Typography variant="body2" color="text.secondary">
        {expiryDate.toLocaleDateString()}
      </Typography>
    );
  };

  // 表格列定义
  const columns: GridColDef[] = [
    {
      field: 'name',
      headerName: '租户名称',
      flex: 1,
      minWidth: 200,
      renderCell: (params: GridRenderCellParams<Tenant>) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <BusinessIcon color="primary" fontSize="small" />
          <Box>
            <Typography variant="subtitle2" noWrap>
              {params.row.name}
            </Typography>
            <Typography variant="caption" color="text.secondary" noWrap>
              {params.row.code}
            </Typography>
          </Box>
        </Box>
      ),
    },
    {
      field: 'subscriptionPlan',
      headerName: '订阅套餐',
      width: 130,
      renderCell: (params: GridRenderCellParams<Tenant>) => (
        <Chip
          label={params.row.subscriptionPlan}
          color="primary"
          variant="outlined"
          size="small"
        />
      ),
    },
    {
      field: 'status',
      headerName: '状态',
      width: 100,
      renderCell: (params: GridRenderCellParams<Tenant>) => 
        renderStatus(params.row.status),
    },
    {
      field: 'expiresAt',
      headerName: '到期时间',
      width: 150,
      renderCell: (params: GridRenderCellParams<Tenant>) => 
        renderExpiryStatus(params.row.expiresAt),
    },
    {
      field: 'settings',
      headerName: '用户数限制',
      width: 120,
      valueGetter: (params) => params.row.settings?.maxUsers || 0,
      renderCell: (params: GridRenderCellParams<Tenant>) => (
        <Typography variant="body2">
          {params.row.settings?.maxUsers || 0}
        </Typography>
      ),
    },
    {
      field: 'createdAt',
      headerName: '创建时间',
      width: 150,
      valueGetter: (params) => new Date(params.row.createdAt).toLocaleDateString(),
    },
    {
      field: 'actions',
      type: 'actions',
      headerName: '操作',
      width: 120,
      getActions: (params: GridRenderCellParams<Tenant>) => {
        const actions = [];

        if (hasPermission('tenant.view')) {
          actions.push(
            <GridActionsCellItem
              icon={<ViewIcon />}
              label="查看"
              onClick={() => navigate(`/tenants/${params.row.id}`)}
            />
          );
        }

        if (hasPermission('tenant.edit')) {
          actions.push(
            <GridActionsCellItem
              icon={<EditIcon />}
              label="编辑"
              onClick={() => navigate(`/tenants/${params.row.id}/edit`)}
            />
          );
        }

        if (hasPermission('tenant.delete')) {
          actions.push(
            <GridActionsCellItem
              icon={<DeleteIcon />}
              label="删除"
              onClick={() => handleDeleteTenant(params.row)}
            />
          );
        }

        actions.push(
          <GridActionsCellItem
            icon={<MoreVertIcon />}
            label="更多"
            onClick={(event) => handleMoreActions(event, params.row)}
          />
        );

        return actions;
      },
    },
  ];

  // 处理删除租户
  const handleDeleteTenant = (tenant: Tenant) => {
    if (window.confirm(`确定要删除租户"${tenant.name}"吗？此操作不可撤销。`)) {
      deleteMutation.mutate(tenant.id);
    }
  };

  // 处理更多操作菜单
  const handleMoreActions = (event: React.MouseEvent<HTMLButtonElement>, tenant: Tenant) => {
    event.stopPropagation();
    setActionMenuAnchor(event.currentTarget);
    setSelectedTenant(tenant);
  };

  // 关闭操作菜单
  const handleCloseActionMenu = () => {
    setActionMenuAnchor(null);
    setSelectedTenant(null);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (window.confirm(`确定要删除选中的 ${selectedRows.length} 个租户吗？此操作不可撤销。`)) {
      batchDeleteMutation.mutate(selectedRows);
    }
  };

  // 清除筛选
  const handleClearFilters = () => {
    setSearchQuery('');
    setStatusFilter('');
    setSubscriptionFilter('');
  };

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载租户列表失败：{(error as any).message}
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="租户管理"
        description="管理系统中的所有租户"
        actions={
          hasPermission('tenant.create') ? (
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => navigate('/tenants/create')}
            >
              创建租户
            </Button>
          ) : undefined
        }
      />

      <Card>
        <CardContent>
          {/* 筛选工具栏 */}
          <Box sx={{ mb: 3, display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              placeholder="搜索租户名称或编码..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              sx={{ minWidth: 300 }}
            />

            <FormControl sx={{ minWidth: 120 }}>
              <InputLabel>状态</InputLabel>
              <Select
                value={statusFilter}
                label="状态"
                onChange={(e) => setStatusFilter(e.target.value as Status)}
              >
                <MenuItem value="">全部</MenuItem>
                <MenuItem value="active">启用</MenuItem>
                <MenuItem value="inactive">禁用</MenuItem>
                <MenuItem value="pending">待审核</MenuItem>
                <MenuItem value="suspended">暂停</MenuItem>
              </Select>
            </FormControl>

            <FormControl sx={{ minWidth: 140 }}>
              <InputLabel>订阅套餐</InputLabel>
              <Select
                value={subscriptionFilter}
                label="订阅套餐"
                onChange={(e) => setSubscriptionFilter(e.target.value)}
              >
                <MenuItem value="">全部</MenuItem>
                {subscriptionPlans?.data?.map((plan) => (
                  <MenuItem key={plan.id} value={plan.name}>
                    {plan.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <Button
              variant="outlined"
              startIcon={<FilterIcon />}
              onClick={handleClearFilters}
            >
              清除筛选
            </Button>

            {selectedRows.length > 0 && hasPermission('tenant.delete') && (
              <Button
                variant="outlined"
                color="error"
                startIcon={<DeleteIcon />}
                onClick={handleBatchDelete}
                disabled={batchDeleteMutation.isLoading}
              >
                批量删除 ({selectedRows.length})
              </Button>
            )}
          </Box>

          {/* 数据表格 */}
          <Box sx={{ height: 600 }}>
            <DataGrid
              rows={tenantData?.data || []}
              columns={columns}
              loading={isLoading}
              paginationMode="server"
              rowCount={tenantData?.total || 0}
              page={page}
              pageSize={pageSize}
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              pageSizeOptions={[10, 25, 50, 100]}
              checkboxSelection={hasPermission('tenant.delete')}
              disableRowSelectionOnClick
              rowSelectionModel={selectedRows}
              onRowSelectionModelChange={(newSelection) => {
                setSelectedRows(newSelection as string[]);
              }}
              slots={{
                toolbar: GridToolbar,
              }}
              slotProps={{
                toolbar: {
                  showQuickFilter: true,
                  quickFilterProps: { debounceMs: 500 },
                },
              }}
              sx={{
                '& .MuiDataGrid-row:hover': {
                  backgroundColor: 'action.hover',
                },
              }}
            />
          </Box>
        </CardContent>
      </Card>

      {/* 更多操作菜单 */}
      <Menu
        anchorEl={actionMenuAnchor}
        open={Boolean(actionMenuAnchor)}
        onClose={handleCloseActionMenu}
        PaperProps={{
          sx: { minWidth: 180 },
        }}
      >
        <MenuList>
          <MenuOption onClick={() => {
            if (selectedTenant) {
              navigate(`/tenants/${selectedTenant.id}`);
            }
            handleCloseActionMenu();
          }}>
            <ListItemIcon>
              <ViewIcon />
            </ListItemIcon>
            <ListItemText primary="查看详情" />
          </MenuOption>
          
          {hasPermission('tenant.edit') && (
            <MenuOption onClick={() => {
              if (selectedTenant) {
                navigate(`/tenants/${selectedTenant.id}/edit`);
              }
              handleCloseActionMenu();
            }}>
              <ListItemIcon>
                <EditIcon />
              </ListItemIcon>
              <ListItemText primary="编辑租户" />
            </MenuOption>
          )}
          
          <MenuOption onClick={() => {
            if (selectedTenant) {
              navigate(`/tenants/plans?tenantId=${selectedTenant.id}`);
            }
            handleCloseActionMenu();
          }}>
            <ListItemIcon>
              <BusinessIcon />
            </ListItemIcon>
            <ListItemText primary="套餐管理" />
          </MenuOption>
        </MenuList>
      </Menu>
    </Box>
  );
};

export default TenantListPage;